<script setup lang="ts">
import YkUploadFile from '@yk/components/upload/upload-file/YkUploadFile.vue'
import { ElForm, UploadUserFile } from 'element-plus'
import YkPictureCropper from '@yk/components/picture-cropper/YkPictureCropper.vue'
import { CountDownTimer, FileUtil } from '@/utils'
import { ElValidator, passwordRule, phoneRule, required } from '@utils/form-rule'
import { sendNoteCodeAPI, updateAvatarAPI, updateCurrentUserAPI, updatePasswordAPI, updatePhoneAPI } from '@/api/system'
import Authorization from '@utils/authorization'
import { removeToken } from '@utils/authorization/token'
import { useAppStore } from '@/pinia'
import { ObjectUtil } from '@utils/object-util'

defineOptions({ name: 'UserInfo' })
const router = useRouter()
const tabActionName = ref('BasicInfo')
const appStore = useAppStore()

onMounted(() => {
  ObjectUtil.updateVal(basicInfoForm.value, appStore.userInfo)
})

// region TODO 头像
const headerFile = ref<UploadUserFile>()
const pictureCropperRef = ref<InstanceType<typeof YkPictureCropper>>()

function headerFileChangeHandle (e) {
  e.url = URL.createObjectURL(e.raw)
  showHeaderFileImageDialog()
}
// region TODO 裁剪
const headerFileImageDialogModel = ref(false)
function showHeaderFileImageDialog () {
  headerFileImageDialogModel.value = true
}
function closeHeaderFileImageDialog () {
  headerFileImageDialogModel.value = false
  headerFile.value && URL.revokeObjectURL(headerFile.value.url)
  headerFile.value = null
}
// 裁剪
async function cutOut () {
  const loading = ElLoading.service({ text: '裁剪中' })
  pictureCropperRef.value.clip(headerFile.value.name).then((file) => {
    loading.text.value = '上传中'
    FileUtil.updateFile(file).then((res) => {
      if (!res) { loading.close(); return }
      updateAvatarAPI({ avatar: res }).then((res) => {
        res.result().then(() => {
          ElMessage.success('已上传')
          Authorization.reloadUser()
          closeHeaderFileImageDialog()
        })
      }).finally(loading.close)
    }).finally()
    // if (tempHeaderImage.value) {
    //   URL.revokeObjectURL(tempHeaderImage.value)
    // }
    // console.log(file)
    // tempHeaderImage.value = URL.createObjectURL(file)
    // ()
  })
  // tempHeaderImage.value = URL.createObjectURL(file)
  // uploadHeadImageAPI(file).then(function (res) {
  //   res.result().then(function (rdata) {
  //     const data = rdata.payload.data
  //     store.commit('app/setUserImage', data)
  //     hideFileImageDialogModel()
  //   })
  // })
}
// endregion
// endregion

// region TODO 修改密码
// region TODO 表单
const changePasswordForm = ref({
  // 确认密码
  confirmPassword: '',
  // 密码
  password: '',
  // 手机号
  phone: '',
  // 短信code
  smsCode: ''
})
const changePasswordFormRef = ref<InstanceType<typeof ElForm>>()
const changePasswordFormRules = ref({
  // 确认密码
  confirmPassword: [{
    validator (rule: any, value: any, callback: (error?: Error) => void) {
      const { password, confirmPassword } = changePasswordForm.value
      callback(password === confirmPassword ? undefined : Error('两次密码不一致'))
    },
    trigger: 'blur',
    required: true
  } as ElValidator],
  // 密码
  password: [required('请输入密码'), passwordRule],
  // 手机号
  phone: [required('请输入手机号'), phoneRule],
  // 短信code
  smsCode: [required('请输入验证码')]
})

function updatePasswordSubmitHandle () {
  changePasswordFormRef.value.validate().then(() => {
    updatePasswordAPI(changePasswordForm.value).then((res) => {
      res.result().then(() => {
        ElMessage.success('密码已修改，需重新的登录')
        removeToken()
        router.replace({ name: 'Login' })
      })
    })
  })
}
// endregion

// region TODO 弹窗
const changePasswordDialogModel = ref(false)
function showChangePasswordDialog () {
  changePasswordDialogModel.value = true
}
function closeChangePasswordDialog () {
  changePasswordDialogModel.value = false
}
// endregion

// region TODO 发送验证码
// 剩余倒计时
const changePasswordRemainingCountdown = ref(0)
const changePasswordCodeCountDownTimer = new CountDownTimer({
  key: 'changePassword',
  toCookie: true,
  fn (e) {
    changePasswordRemainingCountdown.value = e
  }
})

// 发送验证码
function sendChangePasswordVerificationCode () {
  changePasswordFormRef.value.validateField(['phone']).then(() => {
    if (changePasswordForm.value.phone) {
      const loading = ElLoading.service({ text: '正在发送...' })
      sendNoteCodeAPI({
        phone: changePasswordForm.value.phone,
        type: 4
      }).then((res) => {
        res.result().then(() => {
          ElMessage.success('短信已发送，注意查收')
          changePasswordCodeCountDownTimer.run(60)
        })
      }).finally(loading.close)
    }
  })
}
// endregion

// endregion

// region TODO 修改手机号
// region TODO 表单
const changePhoneForm = ref({
  // 手机号
  newPhone: '',
  // 手机号
  oldPhone: '',
  // 短信code
  smsCode: ''
})
const changePhoneFormRef = ref<InstanceType<typeof ElForm>>()
const changePhoneFormRules = ref({
  // 手机号
  newPhone: [required('请输入新手机号'), phoneRule],
  // 手机号
  oldPhone: [required('请输入原手机号')],
  // 短信code
  smsCode: [required('请输入验证码')]
})

function updatePhoneSubmitHandle () {
  changePhoneFormRef.value.validate().then(() => {
    updatePhoneAPI(changePhoneForm.value).then((res) => {
      res.result().then(() => {
        ElMessage.success('手机号已修改')
        Authorization.reloadUser()
      })
    })
  })
}
// endregion

// region TODO 弹窗
const changePhoneDialogModel = ref(false)
function showChangePhoneDialog () {
  changePhoneDialogModel.value = true
}
function closeChangePhoneDialog () {
  changePhoneDialogModel.value = false
}
// endregion

// region TODO 发送验证码 - 原手机号
// 剩余倒计时
// const changePhoneOldRemainingCountdown = ref(0)
// const changePhoneOldCodeCountDownTimer = new CountDownTimer({
//   key: 'changePhoneOld',
//   toCookie: true,
//   fn (e) {
//     changePhoneOldRemainingCountdown.value = e
//   }
// })

// 发送验证码
// function sendChangePhoneOldVerificationCode () {
//   // loginFormRef.value.validateField(['phone']).then(() => {
//   //   if (loginForm.value.phone) {
//   changePhoneOldCodeCountDownTimer.run(60)
//   //   }
//   // })
// }
// endregion

// region TODO 发送验证码 - 新手机号
// 剩余倒计时
const changePhoneNewRemainingCountdown = ref(0)
const changePhoneNewCodeCountDownTimer = new CountDownTimer({
  key: 'changePhoneNew',
  toCookie: true,
  fn (e) {
    changePhoneNewRemainingCountdown.value = e
  }
})

// 发送验证码
function sendChangePhoneNewVerificationCode () {
  changePhoneFormRef.value.validateField(['newPhone']).then(() => {
    if (changePhoneForm.value.newPhone) {
      const loading = ElLoading.service({ text: '正在发送...' })
      sendNoteCodeAPI({
        phone: changePhoneForm.value.newPhone,
        type: 3
      }).then((res) => {
        res.result().then(() => {
          ElMessage.success('短信已发送，注意查收')
          changePhoneNewCodeCountDownTimer.run(60)
        })
      }).finally(loading.close)
    }
  })
}
// endregion
// endregion

// region TODO 基本信息
const basicInfoForm = ref({
  // 公司名称
  corporationName: '',
  // 地址
  address: '',
  // 行业
  profession: ''
})
const basicInfoFormRef = ref<InstanceType<typeof ElForm>>()
function basicInfoFormSubmitHandle () {
  const loading = ElLoading.service()
  updateCurrentUserAPI(basicInfoForm.value).then((res) => {
    res.result().then(() => {
      ElMessage.success('基本信息已修改')
      Authorization.reloadUser().then((user) => {
        ObjectUtil.updateVal(basicInfoForm.value, user)
      })
    })
  }).finally(loading.close)
}
// endregion
</script>

<template>
  <div class="layout_view">
    <!--基本信息-->
    <div class="c_card-white py-32 px-20 d-flex">
      <!--头像-->
      <div style="width: 100px; aspect-ratio: 1;">
        <yk-upload-file
          v-model="headerFile" list-type="picture"
          is-none
          accept="jpg,png"
          @change="headerFileChangeHandle"
        >
          <el-avatar :src="FileUtil.prefixImage(appStore.userInfo.avatar, FileUtil.DefaultImage.Avatar)" :size="100" />
        </yk-upload-file>
      </div>
      <!--基本信息-->
      <el-descriptions :column="2" style="width: 500px;margin-left: 60px;">
        <el-descriptions-item label="用户名：">{{ appStore.userInfo.userName }}</el-descriptions-item>
        <el-descriptions-item label="手机号：">{{ appStore.userInfo._phone }}</el-descriptions-item>
        <el-descriptions-item label="姓名：">{{ appStore.userInfo.nickName }}</el-descriptions-item>
        <el-descriptions-item label="密码：">********</el-descriptions-item>
        <el-descriptions-item label="注册时间：">{{ appStore.userInfo.createdAt }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <!--基本信息 &  安全设置-->
    <div class="mt-16 c_card-white px-20 py-2">
      <el-tabs v-model="tabActionName">
        <el-tab-pane label="基本信息" name="BasicInfo">
          <div class="basic-info p-32">
            <el-form
              ref="basicInfoFormRef" :model="basicInfoForm"
              style="width: 340px;"
              label-width="80px"
            >
              <el-form-item label="公司名称">
                <el-input v-model.trim="basicInfoForm.corporationName" />
              </el-form-item>
              <!--<el-form-item label="所在区域">-->
              <!--  <el-select class="w-100" />-->
              <!--</el-form-item>-->
              <el-form-item label="具体地址">
                <el-input v-model.trim="basicInfoForm.address" />
              </el-form-item>
              <el-form-item label="所属行业">
                <el-input v-model.trim="basicInfoForm.profession" />
              </el-form-item>
            </el-form>
            <!--保存-->
            <div style="margin-top: 60px">
              <el-affix target=".basic-info" position="bottom" :offset="0">
                <div class="c_affix-bg-white text-center c_form__submit-btn">
                  <!--<el-button type="primary" plain>取消</el-button>-->
                  <el-button type="primary" @click="basicInfoFormSubmitHandle">保存</el-button>
                </div>
              </el-affix>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="安全设置" name="SecuritySettings">
          <div class="security-setting p-32">
            <el-form style="width: 340px;" label-width="80px">
              <el-form-item label="手机号">
                <div class="d-flex-center">
                  <el-input readonly :model-value="appStore.userInfo._phone" />
                  <el-link type="primary" style="white-space: nowrap;" class="ml-16" @click="showChangePhoneDialog">修改</el-link>
                </div>
              </el-form-item>
              <el-form-item label="密码">
                <div class="d-flex-center">
                  <el-input readonly model-value="●●●●●●●●" />
                  <el-link type="primary" style="white-space: nowrap;" class="ml-16" @click="showChangePasswordDialog">修改</el-link>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!--头像裁剪-->
    <el-dialog
      v-model="headerFileImageDialogModel" title="裁剪" style="max-width: 600px;width: fit-content;"
      :close-on-click-modal="false"
      @close="closeHeaderFileImageDialog"
    >
      <yk-picture-cropper
        ref="pictureCropperRef"
        style="min-height: 300px;min-width: 300px;" :img="headerFile? headerFile.url : undefined" :compress="{ width: 100 }"
        :aspect-ratio="1"
        shape="circle"
      />
      <template #footer>
        <el-button type="primary" @click="cutOut">裁剪并保存</el-button>
      </template>
    </el-dialog>
    <!--修改密码-->
    <el-dialog
      v-model="changePasswordDialogModel" title="修改密码" width="430px"
      :close-on-click-modal="false"
      draggable @close="closeChangePasswordDialog"
    >
      <el-form
        ref="changePasswordFormRef" class="c_form-save mt-20" :model="changePasswordForm"
        :rules="changePasswordFormRules"
        label-width="110px"
      >
        <el-form-item label="绑定手机号：" prop="phone">
          <el-input v-model.trim="changePasswordForm.phone" />
        </el-form-item>
        <el-form-item label="验证码：" prop="smsCode">
          <el-input v-model.trim="changePasswordForm.smsCode" placeholder="请输入验证码">
            <template #append>
              <el-button :disabled="changePasswordRemainingCountdown > 0" style="width: 110px;" @click="sendChangePasswordVerificationCode">
                <span v-if="changePasswordRemainingCountdown">{{ changePasswordRemainingCountdown }}秒后重试</span>
                <span v-else class="color-primary">获取验证码</span>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码：" prop="password">
          <el-input v-model.trim="changePasswordForm.password" show-password />
        </el-form-item>
        <el-form-item label="再次输入：" prop="confirmPassword">
          <el-input v-model.trim="changePasswordForm.confirmPassword" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="c_form__submit-btn">
          <el-button type="primary" plain @click="closeChangePasswordDialog">取消</el-button>
          <el-button type="primary" @click="updatePasswordSubmitHandle">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!--修改手机号-->
    <el-dialog
      v-model="changePhoneDialogModel" title="修改手机号" width="430px"
      :close-on-click-modal="false"
      draggable @close="closeChangePhoneDialog"
    >
      <el-form
        ref="changePhoneFormRef" class="c_form-save mt-20" :model="changePhoneForm"
        :rules="changePhoneFormRules"
        label-width="100px"
      >
        <el-form-item label="原手机号：" prop="oldPhone">
          <el-input v-model.trim="changePhoneForm.oldPhone" />
        </el-form-item>
        <!--<el-form-item label="验证码：" prop="">-->
        <!--  <el-input placeholder="请输入验证码" show-password>-->
        <!--    <template #append>-->
        <!--      <el-button :disabled="changePhoneOldRemainingCountdown > 0" style="width: 110px;" @click="sendChangePhoneOldVerificationCode">-->
        <!--        <span v-if="changePhoneOldRemainingCountdown">{{ changePhoneOldRemainingCountdown }}s</span>-->
        <!--        <span v-else class="color-primary">获取验证码</span>-->
        <!--      </el-button>-->
        <!--    </template>-->
        <!--  </el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="新手机号：" prop="newPhone">
          <el-input v-model.trim="changePhoneForm.newPhone" />
        </el-form-item>
        <el-form-item label="验证码：" prop="smsCode">
          <el-input v-model.trim="changePhoneForm.smsCode" placeholder="请输入验证码">
            <template #append>
              <el-button :disabled="changePhoneNewRemainingCountdown > 0" style="width: 110px;" @click="sendChangePhoneNewVerificationCode">
                <span v-if="changePhoneNewRemainingCountdown">{{ changePhoneNewRemainingCountdown }}秒后重试</span>
                <span v-else class="color-primary">获取验证码</span>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="c_form__submit-btn">
          <el-button type="primary" plain @click="closeChangePhoneDialog">取消</el-button>
          <el-button type="primary" @click="updatePhoneSubmitHandle">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">

</style>
